package com.nobleoxtechnology.weatherSMS;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.RemoteViews;
import android.widget.Toast;

public class SmallWidgetHandler extends AppWidgetProvider
{
	ComponentName thisWidget = null;
	RemoteViews remoteViews = null;
	AppWidgetManager appWidgetManager = null;

	private String currentTemp;

	private String message = "";
	private String phoneNumber = "";
	private String zipCode = "";

	private String[] delimOptions = { ",", "\n", ".", ";", ")", "(", "{", "}", "=", "-", " " };

	// Message Parsing variables
	private Integer tempLineSplit = 2;
	private Integer tempDelimiter = 0;
	private Integer tempDelimNumber = 0;

	private boolean deleteText = true;
	private boolean hideNotification = true;
	private String filterText = "Weather:";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	{
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		try
		{
			loadMessageParsing(context.getSharedPreferences(null, 0));

			SmsManager sms = SmsManager.getDefault();
			sms.sendTextMessage(phoneNumber, null, message, null, null);
		}
		catch (Exception e)
		{
			Toast error = Toast.makeText(context, "weatherSMS error occurred: " + e.getMessage(), Toast.LENGTH_LONG);
			error.show();
		}
	}
		
	private void loadMessageParsing(SharedPreferences weatherPref)
	{
	    	phoneNumber = weatherPref.getString("phone", "466453");
	    	zipCode = weatherPref.getString("zip", "11110");
	    	message = weatherPref.getString("send", "%zip% weather").replace("%zip%", zipCode);
	    	
			hideNotification = weatherPref.getBoolean("hideNotification", hideNotification);
			deleteText = weatherPref.getBoolean("deleteText", deleteText);
			filterText = weatherPref.getString("filterText", filterText);

	    	tempLineSplit = weatherPref.getInt("spinnerTempLine", tempLineSplit);
	    	tempDelimiter = weatherPref.getInt("spinnerTempDelimiter", tempDelimiter);
	    	tempDelimNumber = weatherPref.getInt("spinnerTempDelimNum", tempDelimNumber);
	        
	        currentTemp = weatherPref.getString("lastTemp", "###");
	}
	    
	@Override
	public void onReceive(Context context, Intent intent)
	{
		super.onReceive(context, intent);
		
		if (!intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
		{
			return;
		}
		
		SharedPreferences weatherPref = context.getSharedPreferences(null, 0);
		
		loadMessageParsing(weatherPref);
		
		Bundle bundle = intent.getExtras();
		SmsMessage[] msgs = null;
		if (bundle != null)
		{
			Object[] pdus = (Object[]) bundle.get("pdus");
			if (pdus != null)
			{
				msgs = new SmsMessage[pdus.length];
				for (int i = 0; i < msgs.length; i++)
				{
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
			}
		}
		
		for (int i = 0; i < msgs.length; i++)
		{
			if (msgs[i].getOriginatingAddress().equals(phoneNumber))
			{
				try
				{
					if (msgs[i].getDisplayMessageBody() != null)
					{
						if (!msgs[i].getDisplayMessageBody().contains(filterText))
						{
							continue;
						}
							
						String[] weatherSMS_array = msgs[i].getDisplayMessageBody().split("\n");
						if (weatherSMS_array.length >= 2)
						{
							String[] temp_array = weatherSMS_array[tempLineSplit].split(
									delimOptions[tempDelimiter]);
								
							// If the temperature isn't a number, then we can assume the text is NOT valid
							// Possibly allow this to be changed in the Advanced screen
							try
							{
								String t = temp_array[tempDelimNumber];
								Integer.valueOf(t.subSequence(0, t.length() - 1).toString());
							}
							catch (NumberFormatException e)
							{
								continue;
							}
								
							// Begin: add degree
							temp_array[tempDelimNumber] = 
								temp_array[tempDelimNumber].concat(" ");
							char[] temperature = temp_array[tempDelimNumber].toCharArray();
																	
							temperature[temp_array[tempDelimNumber].length() - 1] = 
								temperature[temp_array[tempDelimNumber].length() - 2];
									
							temperature[temp_array[tempDelimNumber].length() - 2]= '\u00B0';
							// End: add degree

							currentTemp = new String(temperature);

							Editor weatherPrefEdit = weatherPref.edit();
							weatherPrefEdit.putString("lastTemp", currentTemp);

							if (thisWidget == null || appWidgetManager == null || remoteViews == null)
							{
								thisWidget = new ComponentName(context, SmallWidgetHandler.class);
								appWidgetManager = AppWidgetManager.getInstance(context);
								remoteViews = new RemoteViews(context.getPackageName(), R.layout.small_widget);
							}
							remoteViews.setTextViewText(R.id.weatherTemp, currentTemp);
							appWidgetManager.updateAppWidget(thisWidget, remoteViews);
						}
						else
						{
							continue;
						}
							
						// Deletes from phone number by address and date, since they're essentially a compound primary key
						if (deleteText)
						{
							Uri deleteUri = Uri.parse("content://sms");
							context.getContentResolver().delete(deleteUri, "address=? and date=?", 
									new String[] { phoneNumber, String.valueOf(msgs[i].getTimestampMillis()) });
						}
							
						if (hideNotification)
						{
							abortBroadcast();
						}
						
						break;
					}
				}
				catch (Exception e)
				{
					continue;
				}
			}
		}
	}
}
